package com.sf.dlb.service;


import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.UserWalletInfo;
import com.sf.dlb.jpa.model.WalletLockInfo;
import com.sf.dlb.jpa.repository.UserWalletRepository;
import com.sf.dlb.jpa.repository.WalletLockRepository;
import com.sf.dlb.utils.Arith;
import com.sf.dlb.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class BaseUserWalletService {
    private static Logger logger = LoggerFactory.getLogger(BaseUserWalletService.class);
    @Autowired
    private UserWalletRepository userWalletRepository;
    @Autowired
    private WalletLockRepository walletLockRepository;
    /**
     * 检查-处理解锁中的dlb
     * @return
     */
    public void checkUnlockDlb(int day){
        logger.info("==checkUnlockDlb start day={}",day);
        List<WalletLockInfo> walletLockInfos=walletLockRepository.findByLockStateAndLockTypeAndDelFlag(ResponseConstant.unlock_state_for,ResponseConstant.apply_unlock_dlb,"0",day);
        if(CollectionUtils.isEmpty(walletLockInfos)){
            logger.info("checkUnlockDlb walletLockInfos is  null");
            return;
        }
        logger.info("walletLockInfos size "+walletLockInfos.size());
        for (WalletLockInfo walletLockInfo:walletLockInfos) {
            //更新解锁状态
            walletLockInfo.setLockState(ResponseConstant.unlock_state_complete);
            walletLockInfo.setUpdateDate(new Date());
            walletLockRepository.save(walletLockInfo);
            //更新钱包数量
            String userId=walletLockInfo.getUserId();
            UserWalletInfo userWalletInfo=userWalletRepository.findByUserIdAndDelFlag(userId,"0");
            Double availableDlb=userWalletInfo.getAvailableDlb();
            Double unlockDlb=userWalletInfo.getUnlockDlb();
            availableDlb=(null==availableDlb?0.0:availableDlb);
            Double lockCount=walletLockInfo.getLockCount();
            userWalletInfo.setAvailableDlb(Arith.add(availableDlb,lockCount));//可用数量增加；
            userWalletInfo.setUnlockDlb(Arith.sub(unlockDlb,lockCount));//解锁中数量减少
            userWalletInfo.setUpdateDate(new Date());
            userWalletRepository.save(userWalletInfo);
            logger.info("checkUnlockDlb userWalletInfo={}",GsonUtils.getInstance().toJson(userWalletInfo));
        }
    }
}
